package com.gdth.bank.activity;

import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseActivity;
import com.gdth.http.method.EngDNS;
import com.gdth.utils.GsonUtil;
import com.gdth.utils.UUIDUtil;
import com.gdth.widget.dialog.BaseToast;
import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.adapter.NoteAdapter;
import com.gdth.bank.bean.DownloadBean;
import com.gdth.bank.presenter.ServerPresener;
import com.gdth.bank.utils.ServerUtil;
import com.gdth.bank.view.ServerView;
import com.gdth.database.bean.Note;
import com.gdth.http.callback.DownLoadCallback;
import com.gdth.http.callback.UploadCallback;
import com.gdth.http.listener.UIProgressListener;
import com.gdth.http.listener.impl.UIProgressListenerImpl;
import com.gdth.http.method.ProgressHelper;
import com.gdth.http.method.httpsUtils;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class NoteActivity extends BaseActivity implements ServerView{
	@ViewInject(id=R.id.header_label_title) TextView txt_header_title;
	@ViewInject(id=R.id.header_btn_left, click="finishClick") TextView txt_header_left;
    @ViewInject(id=R.id.header_btn_right) TextView txt_header_right;
    
	@ViewInject(id=R.id.editTextNote) EditText editText;
	@ViewInject(id=R.id.buttonAdd, click="addNote") Button button;
	@ViewInject(id=R.id.upload_progress) ProgressBar uploadProgress;
	@ViewInject(id=R.id.download_progress) ProgressBar downloadProgeress;
	@ViewInject(id=R.id.upload, click="upload") Button upload;
	@ViewInject(id=R.id.download, click="download") Button download;
	
	@ViewInject(id=R.id.listView, itemClick="ItemClick") ListView listView;
	
	List<Note> mListNote;

	NoteAdapter mAdapter; 
	
	ServerPresener<Note> mServerPresener;
	
	private static final OkHttpClient client = new OkHttpClient.Builder()
    //设置超时，不设置可能会报异常
    .connectTimeout(1000, TimeUnit.MINUTES)
    .readTimeout(1000, TimeUnit.MINUTES)
    .writeTimeout(1000, TimeUnit.MINUTES)
	.dns(new EngDNS())
    .sslSocketFactory(httpsUtils.getSSLSocketFactory())
	.hostnameVerifier(httpsUtils.getHostnameVerifier())
    .build();
	
	/** 登录loading提示框 */
    private ProgressDialog mProgressDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_note);
		
		initView();
		
		mServerPresener = new ServerPresener<Note>(this);
		updateData();
	}
	
	private void initView(){
		txt_header_title.setText("数据库测试页面");
		txt_header_right.setVisibility(View.GONE);
		
		mListNote = new ArrayList<Note>();
		
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage("刷新");
		
		mAdapter = new NoteAdapter(this, mListNote);
		listView.setAdapter(mAdapter);
	}
	
	
	private void updateData() {
		mServerPresener.loadAll(new Note());
	}

	public void addNote(View arg0) {
		String noteText = editText.getText().toString();

		final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
		
		String comment = "Added on " + df.format(new Date());
		
		Note note = new Note(null, noteText, comment, new Date());
		
		mServerPresener.save(note);
		
		updateData();
	}

	public void ItemClick(ListView l, View v, int position, long id) {
		mServerPresener.delete(mListNote.get(position));
		updateData();
	}
	
	public void download(View arg0) {
        //这个是非ui线程回调，不可直接操作UI
		DownloadBean bean = new DownloadBean();
		bean.setName("111.txt");
		bean.setScms(0);
		bean.setCjsj(new Date());
		bean.setWybs(UUIDUtil.getUUID());
		
		String content = GsonUtil.getGson().toJson(bean);
        
		String url = BankApplication.mInstance.url + "bank/fileDownLoadOperate!downLoadByName.do?content="+content;
		
        //这个是ui线程回调，可直接操作UI
        final UIProgressListener uiProgressResponseListener = new UIProgressListenerImpl(downloadProgeress);

        //构造请求
        final Request request = new Request.Builder().url(url).build();
        ProgressHelper.addProgressResponseListener(client, uiProgressResponseListener).newCall(request).enqueue(new DownLoadCallback(mHandler));
    }
	
	private Handler mHandler = new Handler(new Handler.Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			
			if (msg.what == 101) {
//				Bundle bundle = msg.getData();
//				String content = bundle.getString("content");
				
//				DownloadBean bean = GsonUtil.getGson().fromJson(content, DownloadBean.class);
			}
			return false;
		}
	});

	public void upload(View arg0) {
		DownloadBean bean = new DownloadBean();
		bean.setName("111");
		bean.setWjlx("png");
		bean.setUuid(UUIDUtil.getUUID());
		bean.setWybs(UUIDUtil.getUUID());
		bean.setLocalPath("/Arecord/1.png");
		bean.setScms(0);
		bean.setCjsj(new Date());
		bean.setGnmk(2);
		
		String content = GsonUtil.getGson().toJson(bean);
        
		String url = BankApplication.mInstance.url + "bank/upload!fileUpload.do?content="+content;

        //此文件必须在手机上存在，实际情况下请自行修改，这个目录下的文件只是在我手机中存在。
        File file = new File(Environment.getExternalStorageDirectory() + bean.getLocalPath());

        //这个是ui线程回调，可直接操作UI
        final UIProgressListenerImpl uiProgressRequestListener = new UIProgressListenerImpl(uploadProgress);

        //构造上传请求，类似web表单
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
//                .addFormDataPart("name", "android.png")
                .addFormDataPart("upload", file.getName(), RequestBody.create(null, file))
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"upload\";filename=\"1.png\""), 
                		RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .build();

        final Request request = new Request.Builder().url(url).build();
        ProgressHelper.addProgressResponseListener(client, requestBody, uiProgressRequestListener).newCall(request).enqueue(new UploadCallback(0));

    }
	
	@Override
	public void updateView(int type, Object Obj) {
		// TODO Auto-generated method stub
		if (type == ServerUtil.server_loadAll){
			@SuppressWarnings("unchecked")
			List<Note> notes = (List<Note>) Obj;
			mListNote.clear();
			for (Note note : notes){
				mListNote.add(note);
			}
			
			mAdapter.notifyDataSetChanged();
		} else if (type == ServerUtil.server_save){
			BaseToast.getInstance().ShowSystemToast(this, "保存成功");
		} else if (type == ServerUtil.server_delete){
			BaseToast.getInstance().ShowSystemToast(this, "删除成功");
		}
	}

	@Override
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub
		mProgressDialog.setMessage(msg);
		mProgressDialog.show();
	}

	@Override
	public void hideProgressDialog() {
		// TODO Auto-generated method stub
		mProgressDialog.dismiss();
	}

	@Override
	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		
	}

}